#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include "list.h"

/*!
  Create a new empty linked list object
  /return The new linked list. NOTE: Not a pointer
*/
List new_List(void)
{
	List list;
	list.Head=0x0;
	list.Tail=0x0;

	list.Append = &list_append;
	list.GetByValue = &list_getbyvalue;
	return list;
}

/*!
  Append a value to the list
  /param list A pointer to the list object
  /param value The value to append to the linked list
*/
void list_append(List *list, void *value)
{
	ListNode *node = (ListNode*)malloc(sizeof(ListNode));
	node->Value=value;
	node->Next=0x0;
	if (list->Tail == 0x0) {
		list->Head = node;
		list->Tail = node;
	}
	else {
		list->Tail->Next = node;
		list->Tail = node;
	}
}

/*!
  Return the first occurrance of a value from the list based on a memory comparison
  Warning: This function doesn't do any bound checking when searching the list. Memory access errors can occur.
  /param list A pointer to the linked list to search
  /param size The number of bytes to match
  /param offset The offset in the value for matching
  /return The first occurance of value in the list
*/
void *list_getbyvalue(List *list, void *value, unsigned int size, unsigned int offset)
{
	ListNode *iter = list->Head;
	while (iter != 0x0)
	{
		if (memcmp(&iter->Value+offset, value, size) == 0)
			return &iter->Value;
		iter = iter->Next;
	}
	return 0x0;
}
